//var sliderWidth = 96; // 需要设置slider的宽度，用于计算中间位置

var http = require('../../../../service/http.js'); //请求类
var util = require('../../../../utils/util.js'); //工具类
var rd_session = '';

const app = getApp();
Page({
  data: {
    //-----------页面加载--------------------------------
    showPage: false, //是否展示页面
    //------------当前页名称-----------------------------
    pageName: 'orders',
    tabs: [{
        name: "全部",
        status: ''
      },
      {
        name: "待付款",
        status: '10'
      },
      {
        name: "待成团",
        status: '11'
      },
      {
        name: "待发货",
        status: '20'
      },
      {
        name: "待收货",
        status: '30'
      },
      {
        name: "已完成",
        status: '50'
      },
    ],
    activeIndex: 0,
    sliderOffset: 0,
    sliderLeft: 0,
    sliderWidth: 60,
    //-----------订单列表相关参数------------------------
    pageNo: 1, //请求商品页数
    total: 0, //分页总页数，
    status: 10, //单个订单订单状态
    orders: [], //所有订单[]
    statusOri: '', //根据 statusOri 查询多种订单
    orderId: '', //订单id
    //----------店铺相关-------------------------
    shopName: '', //店铺名称
  },
  onLoad: function(options) {
    let that = this;
    rd_session = wx.getStorageSync('rd_session');
    if (options.checkOrders == '1') { //通过模板消息进入
      app.checkSession();
      let checkSessionTask = setInterval(function() {
        let isAuthorization = app.data.isAuthorization;
        if (isAuthorization === true || isAuthorization === false) {
          clearInterval(checkSessionTask);
          if (!isAuthorization) {
            app.SessionTimeOut();
            return;
          }
        }
      }, 10)
    }
    app.clearProductLevMsgs();//清空自定义留言信息
    that.showList(options); //加载订单列表
  },

  //-----------------------展示订单列表---------------------------------
  showList: function(options) {
    console.log('展示订单列表', options);
    let that = this;

    that.selectByOrderStatus(options); //根据订单状态查询订单列表

    let activeIndex = 0;
    let statusOri = 0;
    if (options) { //如果orderIndex参数不为空则为支付模板消息入口进入
      activeIndex = options.activeIndex
      statusOri = options.statusOri
    }
    that.setData({
      activeIndex: activeIndex || 0,
      statusOri: statusOri || ''
    })
    //获取用户信息设置，根据orderIndex设置tab位置
    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          sliderWidth: res.windowWidth / 5,
          sliderLeft: (res.windowWidth / that.data.tabs.length - that.data.sliderWidth) / 2,
          sliderOffset: res.windowWidth / that.data.tabs.length * activeIndex,
        });
      }
    });

  },
  onShow: function() {
    if (app.data.shopInfoTimeOut === true) { //非分享且已经过期，清除店铺信息
      console.log('店铺信息已过期，重新加载 app.checkSession()');
      app.checkSession();
    }
    console.log("查询当前订单类型=" + this.data.statusOri);
    this.setData({
      shopName: app.data.shopName, //店铺名称
    })
  },
  //点击tab导航
  tabClick: function(e) { //tab点击事件
    this.setData({
      sliderOffset: e.currentTarget.offsetLeft,
      activeIndex: e.currentTarget.id || 0
    });
  },

  orderDetial: function(e) { //根据id 产看订单详情
    console.log('orderDetial', e);
    let orderId = e.currentTarget.dataset.orderid;
    wx.navigateTo({
      url: '/pages/product/pages/order/order?orderId=' + orderId,
    })

  },
  cancelOrder: function(e) { //关闭订单
    let orderId = e.currentTarget.dataset.orderid;
    let that = this;
    
    wx.showModal({
      title: '',
      content: '确定要取消该订单么？',
      cancelText: '我再想想',
      confirmText: '确定',
      success: function(res) {
        if (res.confirm) {
          http.getReq('/weixin/getOrder/closeOrder', {
            orderId: orderId
          }, function(rr) {
            console.log("取消订单回调" , rr);
            if (rr.ret) {
              util.showToast('订单已取消', 1000, 'none', function() {
                that.setData({ //取消订单后跳转至全部订单
                  statusOri: '',
                  activeIndex: '',
                })
                that.onPullDownRefresh();
              });
            } else {
              app.connectionTimeout(rr.msg);
            }
          }, true, '正在取消订单');

        }
      }
    })
  },

  selectByOrderStatus: function(e) { //根据订单状态查询订单列表
    // console.log("订单状态statusOri=" + e);
    let that = this;
    //页面暂不展示
    that.setData({
      showPage: false, //是否展示订单内容
    })
    let statusOri = that.data.statusOri;
    let activeIndex = that.data.activeIndex;
    if (e || '') {
      //从onload()外部加载方法 所带参数e.statusOri && e.activeIndex 
      if (e.statusOri && e.activeIndex) {
        statusOri = e.statusOri; //根据 statusOri 查询多种订单
        activeIndex = e.activeIndex; //tab下标
      }
      //从订单页面点击加载-------------------------------------------------
      else if (e.currentTarget) {
        statusOri = e.currentTarget.dataset.status; //-订单状态参数
        activeIndex = e.currentTarget.id //tab-id
      }
    }

    //获取用户信息设置，根据orderIndex设置tab位置
    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          sliderOffset: res.windowWidth / that.data.tabs.length * activeIndex,
        });
      }
    });

    //---------------------设置tab位置-----------------------------------
    this.setData({
      statusOri: statusOri || '', //距离屏幕左侧距离
      activeIndex: activeIndex || 0 //tab-id
    });

    //初始化商品列表
    let [pageNo, orders, total] = [1, [], 0];
    that.setData({
      orders: orders,
      pageNo: 1
    })

    //---------------------------请求订单列表-------------------------------  
    http.getReq('/weixin/getOrder/list', {
      rdSession: rd_session,
      pageNo: pageNo,
      pageSize: app.data.pageSize,
      statusOri: statusOri || ''
    }, function(res) {
      console.log('请求订单列表list', res);
      total = res.total; //分页总页数
      orders = res.orders; //查询返回的所有订单
      //设置分页总数和订单
      that.setData({
        total: total,
        orders: orders,
        showPage: true, //加载后展示订单内容
      })
      wx.stopPullDownRefresh(e)
    });

  },
  onPullDownRefresh: function() { //下拉刷新
    this.selectByOrderStatus();
  },
  backToHome: function(e) {
    app.backToHome(this);
  },
  onReachBottom: function(e) { //监听页面到底 分页加载商品
    let that = this;
    let [pageNo, total, statusOri] = [that.data.pageNo, that.data.total, that.data.statusOri];
    //-----------判断是否小于分页总数------------------------
    if (pageNo < total) {
      pageNo = pageNo + 1;

      let orders = that.data.orders; //目前的商品列表
      http.getReq('/weixin/getOrder/list', {
        rdSession: rd_session,
        pageNo: pageNo,
        pageSize: app.data.pageSize,
        statusOri: statusOri
      }, function(res) {
        console.log("返回分页总页数", res);
        total = res.total; //分页总页数
        let newList = res.orders; //查询返回的所有订单

        if (newList.length > 0) {
          orders.push(...newList); //追加数组
        } else { //商品长度为0 没有更多商品了
          console.log('没有更多商品了')
        }
        that.setData({
          orders: orders,
          total: total,
          pageNo: pageNo
        })

      }, true, '加载中');

    }
  },
  //确认收货
  finishOrder: function(e) {
    console.log(e);
    let orderId = e.currentTarget.dataset.orderid;
    let that = this;
    wx.showModal({
      title: '',
      content: '确定收到货物了么？',
      cancelText: '取消',
      confirmText: '确定',
      success: function(res) {
        if (res.confirm) {
          http.getReq('/weixin/getOrder/finishOrder', {
            orderId: orderId
          }, function(res) {
            if (res.ret) {
              util.showToast('确认收货成功', 1000, 'none', function() {
                that.onPullDownRefresh();
              });
            }
          });
        }
      }
    })
  },
  getFormId: function(e) {
    app.getFormId(e);
  },

  //一键复制订单号：
  copyText: function(e) {
    util.copyText(e);
  },
  
});